<?php

namespace App\Dao\Shipping;

use Yj\Daos\BaseDaos;
use App\Model\Shipping\ShippingTemplates;
use Hyperf\Database\Model\Builder;
use Yj\Daos\Verify;
use Hyperf\Utils\Collection;

/**
 * @var ShippingTemplates
 * @method $this params($params)
 */
class ShippingTemplatesDao extends BaseDaos
{
    public function searchParams(Collection $params)
    {
        $search = $this->getSearch();
        $params->check('id', function ($id) use ($search) {
            $search->where('id', $id);
        });
        return $search;
    }

    public function lists(Collection $params)
    {
        $data = $this->params($params)->orderByDesc("id")->getList();
        return $data;
    }

    public function add(Collection $params)
    {
        $data = $this->create($params->toArray());
        return $data;
    }

    public function del(int $id)
    {
        $data = $this->DaoWhere(["id" => $id])->firstOrError();
        return $data->delete();
    }

    public function detail(int $id)
    {
        $data = $this->params(_Collect(['id' => $id]))->with('ShippingTemplatesRegion')->first();
        $ShippingTemplatesRegion = $data->ShippingTemplatesRegion;
        $ShippingTemplatesRegion = $ShippingTemplatesRegion->groupBy('uniqid');
        $ShippingTemplatesRegion->transform(function ($item, $key) {
            $areas_ids = [];
            foreach ($item as $v) {
                $areas_ids[] = [
                    $v['province_id'],
                    $v['city_id']
                ];
            }
            return $item->first()->toArray() + compact('areas_ids');
        });
        $data->setRelation('ShippingTemplatesRegion', $ShippingTemplatesRegion->values());
        return $data->toArray();
    }

}
